package com.party.mobile.biz.gift;

import com.party.common.utils.StringUtils;
import com.party.core.exception.BusinessException;
import com.party.core.model.YesNoStatus;
import com.party.core.model.coupon.Coupon;
import com.party.core.model.coupon.CouponCode;
import com.party.core.model.gift.*;
import com.party.core.model.member.Member;
import com.party.core.model.member.MemberAddress;
import com.party.core.service.coupon.ICouponCodeService;
import com.party.core.service.coupon.ICouponService;
import com.party.core.service.gift.*;
import com.party.core.service.gift.biz.GiftBizService;
import com.party.core.service.member.IMemberAddressService;
import com.party.core.service.member.IMemberService;
import com.party.mobile.biz.file.FileBizService;
import com.party.notify.notifyPush.servce.INotifySendService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author：yifeng
 * @description： 礼包业务处理
 * @date：Created in  2017/11/28 下午 18:51
 **/
@Service
public class GiftOrderBizService {
    @Autowired
    private IMemberAddressService memberAddressService;
    @Autowired
    private IGiftOrderService giftOrderService;
    @Autowired
    private IGiftTargetService giftTargetService;
    @Autowired
    private IGiftService giftService;
    @Autowired
    private ICouponCodeService couponCodeService;
    @Autowired
    private ICouponService couponService;
    @Autowired
    private IGiftCouponService giftCouponService;
    @Autowired
    private INotifySendService notifySendService;
    @Autowired
    private IMemberService memberService;
    @Autowired
    private FileBizService fileBizService;
    @Autowired
    private IGiftMemberService giftMemberService;
    @Autowired
    private GiftBizService giftBizService;

    Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 礼包领取
     *
     * @param currentId 用户id
     * @param targetId  项目id
     * @param gift      礼包
     * @param projectId 众筹id
     * @throws Exception
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void payOrder(String currentId, String targetId, Gift gift, String projectId) {
        // 取默认地址
        MemberAddress memberAddress = memberAddressService.getDefaultAddress(currentId);

        GiftOrder giftOrder = new GiftOrder(currentId, gift.getId(), targetId);
        giftOrder.setGiftNum(String.valueOf(System.currentTimeMillis()));
        giftOrder.setCreateBy(currentId);
        giftOrder.setUpdateBy(currentId);
        giftOrder.setType(gift.getType());
        if (StringUtils.isNotEmpty(projectId)) {
            giftOrder.setProjectId(projectId);
        }
        if (memberAddress != null) {
            giftOrder.setConsigneeName(memberAddress.getName());
            giftOrder.setConsigneePhone(memberAddress.getPhone());
            String allDetail = memberAddress.getShowAddress() + " " + memberAddress.getDetailAddress();
            giftOrder.setConsigneeAddress(allDetail);
        }
        giftOrder.setTargetId(targetId);
        String targetName = giftBizService.getTargetName(gift.getType(), targetId);
        giftOrder.setTargetName(targetName);
        giftOrderService.insert(giftOrder);

        // 领取成功后，将关系删除
        GiftMember giftMember = giftMemberService.getUnique(new GiftMember(gift.getId(), currentId, targetId, projectId, ""));
        if (giftMember != null) {
            giftMemberService.delete(giftMember.getId());
        }

        try {
            synchronized (this) {
                GiftTarget giftTarget = giftTargetService.getUnique(new GiftTarget(targetId, gift.getId()));
                if (null == giftTarget.getSalesNum()) {
                    giftTarget.setSalesNum(1L);
                } else {
                    giftTarget.setSalesNum(giftTarget.getSalesNum() + 1);
                }
                giftTargetService.update(giftTarget);

                if (gift.getSalesNum() == null) {
                    gift.setSalesNum(1L);
                } else {
                    gift.setSalesNum(gift.getSalesNum() + 1);
                }
                giftService.update(gift);
            }
        } catch (Exception e) {
            logger.error("礼包领取——礼包冗余字段处理异常", e);
        }

        if (Gift.MODEL_INVENTED.equals(gift.getModel())) {
            CouponCode couponCode = couponCodeService.randomNotUsed(gift.getId());
            if (couponCode == null) {
                throw new BusinessException("核销码库存不足");
            } else {
                couponCode.setIsUsed(YesNoStatus.YES.getCode()); // 已领取
                couponCodeService.update(couponCode);

                giftOrder.setCouponCodeId(couponCode.getId());
                giftOrderService.update(giftOrder);

                try {
                    String filePath = String.format(GiftOrder.UPLOAD_URL, currentId);
                    String content = couponCode.getVerifyCode();
                    fileBizService.uploadCloudOut(couponCode.getId(), filePath, content, null, false);
                } catch (Exception e) {
                    logger.error("生成票券的二维码异常", e);
                }

                try {
                    synchronized (this) {
                        GiftCoupon giftCoupon = giftCouponService.getUnique(new GiftCoupon(gift.getId(), couponCode.getCouponId()));
                        if (giftCoupon.getSalesNum() == null) {
                            giftCoupon.setSalesNum(1L);
                        } else {
                            giftCoupon.setSalesNum(giftCoupon.getSalesNum() + 1);
                        }
                        giftCouponService.update(giftCoupon);

                        Coupon coupon = couponService.get(couponCode.getCouponId());
                        if (coupon.getSalesNum() == null) {
                            coupon.setSalesNum(1L);
                        } else {
                            coupon.setSalesNum(coupon.getSalesNum() + 1);
                        }
                        couponService.update(coupon);
                    }
                } catch (Exception e) {
                    logger.error("礼包领取——票券冗余字段处理异常", e);
                }

                try {
                    Member member = memberService.get(currentId);
                    notifySendService.sendCouponOrder(member.getMobile(), couponCode.getCouponId(), couponCode.getVerifyCode(), gift);
                } catch (Exception e) {
                    logger.error("礼包领取——票券领取推送异常", e);
                }
            }
        } else if (Gift.MODEL_MATTER.equals(gift.getModel())) {
            try {
                Member member = memberService.get(currentId);
                notifySendService.sendGiftOrder(member.getMobile(), gift);
            } catch (Exception e) {
                logger.error("礼包领取——票券领取推送异常", e);
            }
        }
    }
}
